package com.example.librarymanagementsystem2.controllor;

import com.example.librarymanagementsystem2.entity.Book;
import com.example.librarymanagementsystem2.mapper.BookMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Tag(name="LibraryController",description = "图书管理")
@Controller
@SessionAttributes("books")
@RequestMapping("/book")
public class LibraryControllor {
    @Resource
    BookMapper bookMapper;
//    @RequestMapping("/")
//    public String log(HttpSession session) {
//        if(session.getAttribute("login_state")!=null)
//            return "bookList";
//        return "log";
//    }
//    @RequestMapping("/login")
//    public String testLog(Model model, @RequestParam String name, @RequestParam String password,
//                           HttpSession session)
//    {
//        if(session.getAttribute("login_state")!=null)
//            return "bookList";
//        if(name.equals("dcx")&&password.equals("123")) {
//            List<Book> books=bookMapper.selectList(null);
//            model.addAttribute("books",books);
//            session.setAttribute("login_state","yes");
//            System.out.println("YES");
//            return "bookList";
//
//        }
//        return "log";
//    }
    @Operation(summary = "获取整个图书列表",description = "需要登录后访问")
    @GetMapping("/bookList")
    public String bookList(Model model) {
        List<Book> books=bookMapper.selectList(null);
        model.addAttribute("books",books);
        return "book/bookList";
    }
    @Operation(summary = "登记新增图书",description = "返回新的登记界面")
    @GetMapping("/recordBook")
    public String recordBook() {

        return "book/recordBook";
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
    public static boolean judgeIsValid(Book newbook,String filename)
    {
        System.out.println(filename);
        if(filename.equals("")||newbook.getAuthor().equals("")||newbook.getBookname().equals("")||newbook.getPress().equals("")||newbook.getIntro().equals("")||newbook.getPublicationdate().equals("")||newbook.getStock().equals(""))
        {
            return false;
        }
        if(isInteger(newbook.getStock())==false)
        {
            return false;
        }
        int stockNum=Integer.parseInt(newbook.getStock());
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd" );

        Date date = null;
        try {
            date = sdf.parse(newbook.getPublicationdate());
            System.out.println(date);
            Date now=new Date();
            System.out.println(now);
            if(now.before(date))
                return false;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }


        if(stockNum<0)
        {
            return false;
        }
        return true;
    }
    @Operation(summary = "在数据库新增图书信息",description = "在后端完成信息验证")
    @PostMapping("/addbook")
    public String addBook(
                            @RequestParam MultipartFile file,
                            @ModelAttribute Book newbook
                          ){
        String filename=file.getOriginalFilename();
        if(!judgeIsValid(newbook,filename))
            return "book/recordBook";

        List<Book> books=bookMapper.selectList(null);
        filename=newbook.getId()+filename;
        newbook.setFilename(filename);//保存上传的文件
        String parentDir = "D:\\study\\Java_code\\library-management-system2\\src\\main\\resources\\static\\images";
        File parent=new File(parentDir);
        File dest=new File(parent,filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        bookMapper.insert(newbook);
        return "book/success";
    }
    @Operation(summary = "删除某个图书的信息")
    @GetMapping("/delete")
    public String delete(@RequestParam long id)
    {
        //删除原来的封面

        Book book=bookMapper.selectById(id);
        String parentDir = "D:\\study\\Java_code\\library-management-system2\\src\\main\\resources\\static\\images\\";
        String oldPath=parentDir+book.getFilename();

        File dest=new File(oldPath);
        if(dest.exists())
        {
            dest.delete();
        }
        bookMapper.deleteById(id);
        return "book/success";
    }
    @Operation(summary = "编辑图书信息",description = "获取新的编辑界面")
    @GetMapping("/edit")
    public String edit(Model model,@RequestParam long id)
    {
        Book book=bookMapper.selectById(id);
        model.addAttribute("oldbook",book);
        return "book/edit";
    }
    @Operation(summary = "编辑图书信息",description = "由浏览器上传编辑后的信息")
    @PostMapping("/edit")
    public String update(@ModelAttribute Book book,@RequestParam long id,
                         @RequestParam MultipartFile file)
    {
        if(!judgeIsValid(book,file.getOriginalFilename()))
            return "book/error";
        if(!file.isEmpty())
        {
            Book oldbook=bookMapper.selectById(id);
            String parentDir = "D:\\study\\Java_code\\library-management-system2\\src\\main\\resources\\static\\images\\";
            String oldPath=parentDir+oldbook.getFilename();
            System.out.println("oldpath"+oldPath);
            File dest=new File(oldPath);
            if(dest.exists())
            {
                dest.delete();
            }
            String filename=file.getOriginalFilename();
            filename=book.getId()+filename;
            book.setFilename(filename);
            System.out.println(filename);
            //保存上传的文件
            parentDir = "D:\\study\\Java_code\\library-management-system2\\src\\main\\resources\\static\\images";
            File parent=new File(parentDir);
            dest=new File(parent,filename);
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        bookMapper.updateById(book);


        return "book/success";
    }
}
